# 这个文件包含ui_module.py中需要实现的方法

# 初始设置页面方法
def select_ffmpeg_path(self):
    """选择FFmpeg路径"""
    file_dialog = QFileDialog(self)
    file_dialog.setWindowTitle("选择FFmpeg可执行文件")
    file_dialog.setNameFilter("可执行文件 (*.exe)")
    file_dialog.setFileMode(QFileDialog.ExistingFile)
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            ffmpeg_path = selected_files[0]
            self.ffmpeg_path = ffmpeg_path
            self.ffmpeg_path_edit.setText(ffmpeg_path)
            self.append_log(f"已设置FFmpeg路径: {ffmpeg_path}")
            
            # 更新硬件检测线程中的FFmpeg路径
            self.hardware_thread.set_ffmpeg_path(ffmpeg_path)
            self.hardware_thread.start()

# 视频处理页面方法
def select_input_video(self):
    """选择输入视频"""
    file_dialog = QFileDialog(self)
    file_dialog.setWindowTitle("选择输入视频")
    file_dialog.setNameFilter("视频文件 (*.mp4 *.avi *.mkv *.mov *.wmv)")
    file_dialog.setFileMode(QFileDialog.ExistingFile)
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            video_path = selected_files[0]
            self.input_video = video_path
            self.video_path_edit.setText(video_path)
            self.append_log(f"已选择输入视频: {video_path}")

# 左右眼合并页面方法
def select_left_video(self):
    """选择左眼视频"""
    file_dialog = QFileDialog(self)
    file_dialog.setWindowTitle("选择左眼视频")
    file_dialog.setNameFilter("视频文件 (*.mp4 *.avi *.mkv *.mov *.wmv)")
    file_dialog.setFileMode(QFileDialog.ExistingFile)
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            video_path = selected_files[0]
            self.left_eye_video = video_path
            self.left_video_edit.setText(video_path)
            self.append_log(f"已选择左眼视频: {video_path}")

def select_right_video(self):
    """选择右眼视频"""
    file_dialog = QFileDialog(self)
    file_dialog.setWindowTitle("选择右眼视频")
    file_dialog.setNameFilter("视频文件 (*.mp4 *.avi *.mkv *.mov *.wmv)")
    file_dialog.setFileMode(QFileDialog.ExistingFile)
    
    if file_dialog.exec_():
        selected_files = file_dialog.selectedFiles()
        if selected_files:
            video_path = selected_files[0]
            self.right_eye_video = video_path
            self.right_video_edit.setText(video_path)
            self.append_log(f"已选择右眼视频: {video_path}")

# 通用方法
def update_hardware_options(self, hardware_info):
    """更新硬件加速选项"""
    # 清空下拉列表
    self.ffmpeg_accel_combo.clear()
    self.midas_accel_combo.clear()
    
    # 添加FFmpeg加速选项
    for accel in hardware_info["ffmpeg"]["acceleration"]:
        self.ffmpeg_accel_combo.addItem(accel)
    
    # 添加MiDaS加速选项
    for accel in hardware_info["midas"]["acceleration"]:
        self.midas_accel_combo.addItem(accel)
    
    # 更新FFmpeg路径
    if hardware_info["ffmpeg"]["available"] and hardware_info["ffmpeg"]["path"]:
        self.ffmpeg_path = hardware_info["ffmpeg"]["path"]
        self.ffmpeg_path_edit.setText(self.ffmpeg_path)
    
    self.append_log("硬件加速选项已更新")

def append_log(self, message):
    """添加日志"""
    self.log_text.append(message)
    # 滚动到底部
    self.log_text.verticalScrollBar().setValue(self.log_text.verticalScrollBar().maximum())

def start_processing(self):
    """开始处理视频"""
    # 检查是否已设置FFmpeg路径
    if not self.ffmpeg_path or not os.path.exists(self.ffmpeg_path):
        QMessageBox.warning(self, "警告", "请先设置FFmpeg路径")
        return
    
    # 检查是否已选择输入视频
    if not self.input_video or not os.path.exists(self.input_video):
        QMessageBox.warning(self, "警告", "请先选择输入视频")
        return
    
    # 获取帧率和模型
    self.fps = self.fps_edit.value()
    self.model = self.model_combo.currentText()
    
    # 获取硬件加速选项
    self.ffmpeg_accel = self.ffmpeg_accel_combo.currentText()
    self.midas_accel = self.midas_accel_combo.currentText()
    
    # 禁用按钮
    self.process_start_btn.setEnabled(False)
    self.process_cancel_btn.setEnabled(True)
    
    # 创建输出目录
    output_dir = os.path.dirname(self.input_video)
    frames_dir = os.path.join(output_dir, "frames")
    depth_dir = os.path.join(output_dir, "depth")
    left_eye_dir = os.path.join(output_dir, "left_eye")
    right_eye_dir = os.path.join(output_dir, "right_eye")
    
    for dir_path in [frames_dir, depth_dir, left_eye_dir, right_eye_dir]:
        if not os.path.exists(dir_path):
            os.makedirs(dir_path)
    
    # 第一步：使用FFmpeg提取帧
    self.append_log("===== 步骤1：提取视频帧 =====")
    self.ffmpeg_thread = FFmpegProcessor(self.ffmpeg_path, self.ffmpeg_accel)
    self.ffmpeg_thread.input_video = self.input_video
    self.ffmpeg_thread.fps = self.fps
    self.ffmpeg_thread.operation_type = "extract_frames"
    
    self.ffmpeg_thread.progress_updated.connect(lambda p: self.update_progress(p, "提取帧"))
    self.ffmpeg_thread.log_message.connect(self.append_log)
    self.ffmpeg_thread.process_completed.connect(lambda success, msg: self.on_frames_extracted(success, msg, frames_dir, depth_dir, left_eye_dir, right_eye_dir))
    
    self.ffmpeg_thread.start()

def on_frames_extracted(self, success, message, frames_dir, depth_dir, left_eye_dir, right_eye_dir):
    """帧提取完成回调"""
    if not success:
        self.append_log(f"帧提取失败: {message}")
        self.process_start_btn.setEnabled(True)
        self.process_cancel_btn.setEnabled(False)
        return
    
    # 第二步：生成深度图
    self.append_log("\n===== 步骤2：生成深度图 =====")
    
    # 确保正确传递硬件加速选项
    hardware_accel = "cuda" if self.midas_accel.lower() in ["cuda", "gpu"] else "cpu"
    
    # 记录实际使用的加速选项
    self.append_log(f"MiDaS加速选项: {self.midas_accel} -> 使用: {hardware_accel}")
    
    self.depth_thread = DepthGenerator(hardware_accel)
    self.depth_thread.frames_dir = frames_dir
    self.depth_thread.depth_dir = depth_dir
    self.depth_thread.model_type = self.model
    
    self.depth_thread.progress_updated.connect(lambda p: self.update_progress(p, "生成深度图"))
    self.depth_thread.log_message.connect(self.append_log)
    self.depth_thread.process_completed.connect(lambda success, msg: self.on_depth_generated(success, msg, frames_dir, depth_dir, left_eye_dir, right_eye_dir))
    
    self.depth_thread.start()

def on_depth_generated(self, success, message, frames_dir, depth_dir, left_eye_dir, right_eye_dir):
    """深度图生成完成回调"""
    if not success:
        self.append_log(f"深度图生成失败: {message}")
        self.process_start_btn.setEnabled(True)
        self.process_cancel_btn.setEnabled(False)
        return
    
    # 第三步：生成左右眼视图
    self.append_log("\n===== 步骤3：生成左右眼视图 =====")
    self.stereo_thread = StereoGenerator()
    self.stereo_thread.frames_dir = frames_dir
    self.stereo_thread.depth_dir = depth_dir
    self.stereo_thread.left_eye_dir = left_eye_dir
    self.stereo_thread.right_eye_dir = right_eye_dir
    
    # 设置硬件加速选项
    self.stereo_thread.set_hardware_accel(self.stereo_accel)
    
    # 设置视差强度
    shift_strength = self.shift_strength_slider.value() / 100.0
    self.stereo_thread.set_shift_strength(shift_strength)
    
    # 设置并行处理选项
    use_parallel = self.parallel_check.isChecked()
    num_workers = self.threads_spin.value()
    self.stereo_thread.set_parallel_processing(use_parallel, num_workers)
    
    self.stereo_thread.progress_updated.connect(lambda p: self.update_progress(p, "生成左右眼视图"))
    self.stereo_thread.log_message.connect(self.append_log)
    self.stereo_thread.process_completed.connect(lambda success, msg: self.on_stereo_generated(success, msg, left_eye_dir, right_eye_dir))
    
    self.stereo_thread.start()

def on_stereo_generated(self, success, message, left_eye_dir, right_eye_dir):
    """左右眼视图生成完成回调"""
    if not success:
        self.append_log(f"左右眼视图生成失败: {message}")
        self.process_start_btn.setEnabled(True)
        self.process_cancel_btn.setEnabled(False)
        return
    
    # 第四步：合成左右眼视频
    self.append_log("\n===== 步骤4：合成左右眼视频 =====")
    
    # 创建左眼视频路径
    left_video_path = os.path.join(os.path.dirname(left_eye_dir), "left_eye.mp4")
    right_video_path = os.path.join(os.path.dirname(right_eye_dir), "right_eye.mp4")
    
    # 使用FFmpeg线程来创建视频，避免阻塞GUI
    self.ffmpeg_thread = FFmpegProcessor(self.ffmpeg_path, self.ffmpeg_accel)
    self.ffmpeg_thread.frames_dir = left_eye_dir
    self.ffmpeg_thread.output_video = left_video_path
    self.ffmpeg_thread.operation_type = "create_video"
    self.ffmpeg_thread.fps = self.fps
    
    self.ffmpeg_thread.progress_updated.connect(lambda p: self.update_progress(p, "合成左眼视频"))
    self.ffmpeg_thread.log_message.connect(self.append_log)
    self.ffmpeg_thread.process_completed.connect(lambda success, msg: self.on_left_video_created(success, msg, right_eye_dir, right_video_path))
    
    self.ffmpeg_thread.start()

def on_left_video_created(self, success, message, right_eye_dir, right_video_path):
    """左眼视频创建完成回调"""
    if not success:
        self.append_log(f"左眼视频创建失败: {message}")
        self.process_start_btn.setEnabled(True)
        self.process_cancel_btn.setEnabled(False)
        return
    
    # 创建右眼视频
    self.ffmpeg_thread = FFmpegProcessor(self.ffmpeg_path, self.ffmpeg_accel)
    self.ffmpeg_thread.frames_dir = right_eye_dir
    self.ffmpeg_thread.output_video = right_video_path
    self.ffmpeg_thread.operation_type = "create_video"
    self.ffmpeg_thread.fps = self.fps
    
    self.ffmpeg_thread.progress_updated.connect(lambda p: self.update_progress(p, "合成右眼视频"))
    self.ffmpeg_thread.log_message.connect(self.append_log)
    self.ffmpeg_thread.process_completed.connect(self.on_right_video_created)
    
    self.ffmpeg_thread.start()

def on_right_video_created(self, success, message):
    """右眼视频创建完成回调"""
    if not success:
        self.append_log(f"右眼视频创建失败: {message}")
    else:
        self.append_log("左右眼视频创建成功！")
    
    # 处理完成，启用按钮
    self.process_start_btn.setEnabled(True)
    self.process_cancel_btn.setEnabled(False)
    
    # 更新进度条为100%
    self.update_progress(100, "视频处理")